/*
 * RemoveDocumentDestination.java
 *
 * Created on January 4, 2005, 2:42 PM
 */

package org.infoset.xml.filter;

import java.util.*;
import org.infoset.xml.*;

/**
 *
 * @author R. Alexander Milowski
 */
public class RemoveDocumentFilter implements ItemFilter {
   List names;
   int level;
   ItemDestination dest;
   public RemoveDocumentFilter(ItemDestination dest) {
      attach(dest);
      this.names = new ArrayList();
      this.level = -1;
   }

   public void send(Item item) throws XMLException
   {
      switch (item.getType()) {
         case DocumentItem:
            level = -1;
            break;
         case DocumentEndItem:
            break;
         case ElementItem:
            level++;
            names.add(((Element)item).getName());
            dest.send(item);
            break;
         case ElementEndItem:
            if (level<0) {
               throw new XMLException("Unbalanced document: received end element "+((ElementEnd)item).getName());
            }
            names.remove(level);
            level--;
            dest.send(item);
            break;
         default:
            dest.send(item);
      }
   }
   
   public int getLevel() {
      return level;
   }

   public void primeItemConstructor(ItemConstructor constructor) 
      throws XMLException
   {
      for (int i=0; i<=level; i++) {
         constructor.createElement((Name)names.get(i));
      }
   }
   public void closeElementsToLevel(ItemConstructor constructor,int toLevel) 
      throws XMLException
   {
      while (toLevel<=level) {
         Name nm = (Name)names.remove(level);
         level--;
         dest.send(constructor.createElementEnd(nm));
      }
   }
   
   public void closeElements(ItemConstructor constructor) 
      throws XMLException
   {
      closeElementsToLevel(constructor,0);
   }

   public void attach(ItemDestination output)
   {
      this.dest = output;
      this.level = -1;
   }

}
   